package com.net.okhttphelper.interceptor;

import com.net.okhttphelper.download.DownloadListener;
import com.net.okhttphelper.download.ProgressResponseBody;
import com.net.okhttphelper.upload.ProgressRequestBody;
import com.net.okhttphelper.upload.UploadListener;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 进度拦截器
 * @author jie
 */
public class ProgressInterceptor implements Interceptor {

    private ProgressInterceptor(){
    }

    public static ProgressInterceptor build(){
        return new ProgressInterceptor();
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        // 获取初始请求
        Request rawRequest = chain.request();
        // 获取上传监听对象
        UploadListener uploadListener = rawRequest.tag(UploadListener.class);
        // 获取下载监听对象
        DownloadListener downloadListener = rawRequest.tag(DownloadListener.class);
        // 替换请求对象
        Request request = replaceRequest(rawRequest, uploadListener);
        // 执行请求
        Response response = chain.proceed(request);
        // 替换返回对象
        return replaceResponse(response, downloadListener);
    }

    /**
     * 替换为带进度的Request对象
     */
    private Request replaceRequest(Request request, UploadListener uploadListener){
        RequestBody body = request.body();
        if (body == null || uploadListener == null){
            return request;
        }
        // 构造带进度的RequestBody对象
        ProgressRequestBody progressRequestBody = new ProgressRequestBody(body, uploadListener);
        return request.newBuilder().method(request.method(), progressRequestBody).build();
    }

    /**
     * 替换为带进度的Response对象
     */
    private Response replaceResponse(Response response, DownloadListener downloadListener) {
        ResponseBody body = response.body();
        if (body == null || downloadListener == null){
            return response;
        }
        // 构造带进度的ResponseBody对象
        ProgressResponseBody progressResponseBody = new ProgressResponseBody(body, downloadListener);
        return response.newBuilder().body(progressResponseBody).build();
    }
}
